# -*- coding: utf-8 -*-

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
from urllib.parse import  urlencode
from threading import Thread

class Spider(object):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "泰康全能保（2017）保险产品计划"
    # 生产产品数据
    def genProductInfo(self):
        plan = {
            "planA":{
                # 年龄段
                "year":[str(i) for i in range(18,51)],
                # 性别
                "gender":["M","F"],
                # 保障金额
                "money":[str(i) + "0000" for i in range(5,35,5)],
                # 缴费期间
                "interval":["0","5","10","15","20"],
                #保障期间
                "expire":["30年"],
                # 投保对象
                "payObject":["自己/儿女/配偶/父母"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(18, 61)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": [str(i) + "0000" for i in range(5, 35, 5)],
                # 缴费期间
                "interval": ["0", "5", "10", "15", "20"],
                # 保障期间
                "expire": ["至70岁","至80岁"],
                # 投保对象
                "payObject": ["自己/儿女/配偶/父母"]
            }
        }
        for k in plan:

            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["interval"],plan[k]["expire"],plan[k]["payObject"]):

                if v[3] == "0":

                    payType = "一次性缴清"

                else:

                    payType = "年缴"

                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(


                    v[0],v[1],v[2],payType,v[3],v[4],v[5]
                ))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format(


                    v[0],v[1],v[2],payType,v[3],v[4],v[5]
                ))
    #执行爬虫
    def requestJson(self,dt=None,mysql=None):

        if dt["expire"] == "30年":

            expire = "30_Y"

        elif dt["expire"] == "至70岁":

            expire = "70_A"

        else:

            expire = "80_A"

        data = {
            "codeFlag": "3",
            "productNo": "A64",
            "poltype": "01",
            "responsibility": "A64",
            "insuredGender": "M",
            "birthday": "{year} - 01 - 01".format( year = str(2020-int(dt["year"]))),
            "applicantGender": dt["gender"],
            "holderBirthday": "{year} - 01 - 01".format( year = str(2020-int(dt["year"]))),
            "paymentDuration": "1" if dt["interval"] == "0" else dt["interval"],
            "paymentMode": "01",
            "insureDuration": expire,
            "coverageAmount": str(int(int(dt["money"])/10000)),
        }

        payload = urlencode( data ).replace("+","")

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and "grossPremium" in r.text:

            price = Helper.decimalParse( r.json()["grossFirstPremium"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            mysql.updatePrice( data )
        else:
            data = {

                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("/*更新产品价格失败:%d*/"%dt["id"])


    def main(self, mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt, mysql)

    def startProcess(self):

        for i in range(5):

            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))
            # p = Thread( target=self.test,args=(mysql,))

            t.start()

